package com.whoimi.common.config;



import com.whoimi.common.BusiException;
import com.whoimi.common.NotifyException;
import com.whoimi.common.ResultInfo;
import com.whoimi.common.service.WeComBotService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * 异常拦截处理
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionAdvice.class);
    @Resource
    private WeComBotService weComBotService;
    @Value("${spring.application.name}")
    private String applicationName;

    private String hostName = "localhost";
    private String hostAddress = "127.0.0.1";

    @PostConstruct
    public void postConstruct() {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            hostName = localHost.getHostName();
            hostAddress = localHost.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("InetAddress.getLocalHost() error", e);
        }

    }

    /**
     * 自定义异常捕捉处理
     */
    @ExceptionHandler(value = BusiException.class)
    public ResponseEntity<Object> busiException(BusiException e) {
        Integer errorCode = e.getErrorCode();
        String errorMessage = e.getErrorMessage();
        log.error("BusiException getErrorCode:{}, getErrorMessage:{},getMessage:{}", errorCode, errorMessage, e.getMessage());
        return ResponseEntity.ok()
                .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8))
//                .header("errorCode", errorCode).header("errorMessage", errorMessage)
                .body(ResultInfo.fail(errorCode, errorMessage));
    }

    @ExceptionHandler(value = NotifyException.class)
    public ResponseEntity<Object> notifyException(NotifyException e) {
        StackTraceElement stackTraceElement = e.getStackTrace()[0];
        String fileName = Optional.ofNullable(stackTraceElement.getFileName()).map(s -> s.substring(0, s.lastIndexOf(".") + 1)).orElse("");
        String methodName = stackTraceElement.getMethodName();
        int lineNumber = stackTraceElement.getLineNumber();
        String message = e.getMessage();
        String notifyStr = applicationName + " " + hostName + " " + fileName + " " + methodName + "() line:" + lineNumber + " msg:" + message;
        Integer errorCode = e.getErrorCode();
        String errorMessage = e.getErrorMessage();
        log.error("notifyException getErrorCode:{}, getErrorMessage:{},getMessage:{}", errorCode, errorMessage, message, e);
        weComBotService.botSend(notifyStr);
        return ResponseEntity.ok()
                .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8))
                .body(ResultInfo.fail(errorCode, errorMessage));
    }


    /**
     * 全局异常捕捉处理
     */
    @ExceptionHandler(value = Throwable.class)
    public ResponseEntity<Object> globalException(Throwable e) {
        String message = e.getMessage();
        log.error("globalException ,hostName:{},hostAddress:{},getMessage:{}", hostName, hostAddress, message, e);
        return ResponseEntity.badRequest()
                .contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8))
                .body(ResultInfo.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), hostName + ":" + message));
    }
}
